import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

class SelectPeriodsComponent extends StatefulWidget {
  /// 开始时间
  final DateTime startDateTime;

  /// 结束时间
  final DateTime endDateTime;

  /// 组件顶部到appbar底部的距离
  final double distanceToAppbar;

  /// 选择结果回调 标签
  final Function(BaseDateTypeEnum dateTypeEnum, String startDate, String endDate) selectResultCallback;

  /// 设置自定义时间的显示方式
  final String Function(DateTime customizeDate) setCustomizeDateDisplayed;

  const SelectPeriodsComponent({Key key, this.distanceToAppbar = 0.0, @required this.selectResultCallback, this.startDateTime, this.endDateTime, this.setCustomizeDateDisplayed}) : super(key: key);

  @override
  _SelectPeriodsComponentState createState() => _SelectPeriodsComponentState();
}

class _SelectPeriodsComponentState extends State<SelectPeriodsComponent> {
  /// 标签列表
  List<BaseDateTypeEnum> labelList = [BaseDateTypeEnum.today, BaseDateTypeEnum.yesterday, BaseDateTypeEnum.week, BaseDateTypeEnum.lastWeek, BaseDateTypeEnum.month, BaseDateTypeEnum.lastMonth, BaseDateTypeEnum.year, BaseDateTypeEnum.lastYear];

  /// 系统颜色 黑 Color(0xff333333) 白：Color(0xffffffff) 黑白主题选中颜色为Color(0xFFFF004F)
  Color get systemColor => Theme.of(context).primaryColor == Colors.white ? Color(0xFF333333) : Theme.of(context).primaryColor;

  ///标题栏（appbar）
  static double appbarHeight = 0.0;

  /// 标签高度
  final double labelItemHeight = 32;

  DateTime nowDate;

  /// 当前选择的标签
  BaseDateTypeEnum dateTypeEnum = BaseDateTypeEnum.today;

  /// 自定义时间段
  DateTime customizeStart;
  DateTime customizeEnd;

  @override
  void initState() {
    super.initState();
    nowDate = DateTime.now();
    appbarHeight = widget.distanceToAppbar == null ? AppBar().preferredSize.height : AppBar().preferredSize.height + widget.distanceToAppbar;
    initDateTime();
  }

  /// 初始化时间标签
  void initDateTime() {
    if (widget.startDateTime == null || widget.endDateTime == null) return;
    dateTypeEnum = BaseDateUtil.getCurrDateTypeEnum(widget.startDateTime, widget.endDateTime);
    if (dateTypeEnum == BaseDateTypeEnum.customize) {
      customizeStart = DateTime(widget.startDateTime.year, widget.startDateTime.month, widget.startDateTime.day);
      customizeEnd = DateTime(widget.endDateTime.year, widget.endDateTime.month, widget.endDateTime.day, 23, 59, 58);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: SafeArea(
        child: Center(
          child: Column(
            children: [
              SizedBox(height: appbarHeight),
              Expanded(
                child: Container(
                  color: Color(0XAA000000),
                  child: Column(
                    children: [
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.symmetric(horizontal: 16.0),
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8))),
                        child: buildContent(),
                      ),
                      Expanded(child: InkWell(onTap: () => BaseRouterUtil().pop(), child: Container())),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(height: 10.0),
        buildLabelWrap(),
        SizedBox(height: 10.0),
        buildCustomizeLabel(),
        SizedBox(height: 10.0),
      ],
    );
  }

  /// 标签Wrap
  Widget buildLabelWrap() {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        double itemWidth = (constraints.maxWidth - (12 * 3)) / 4;
        return Wrap(
          spacing: 12,
          runSpacing: 10,
          children: labelList.map<Widget>((e) => labelItem(itemWidth, e)).toList(),
        );
      },
    );
  }

  /// 标签item
  Widget labelItem(double itemWidth, BaseDateTypeEnum typeEnum) {
    bool isSelect = dateTypeEnum == typeEnum;
    return Container(
      height: labelItemHeight,
      width: itemWidth,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(2),
        border: Border.all(color: isSelect ? Color(0xFF333333) : Theme.of(context).scaffoldBackgroundColor),
        color: isSelect ? Colors.white : Theme.of(context).scaffoldBackgroundColor,
      ),
      child: InkWell(
        onTap: () => onClickLabel(typeEnum),
        child: Container(width: itemWidth / 2, alignment: Alignment.center, child: Text(BaseDateUtil.getCurrLabelForDateTypeEnum(typeEnum), style: TextStyle(color: isSelect ? systemColor : DefaultTextStyle.of(context).style.color))),
      ),
    );
  }

  /// 自定义标签
  Widget buildCustomizeLabel() {
    bool isSelect = dateTypeEnum == BaseDateTypeEnum.customize;
    return Container(
      width: double.infinity,
      height: labelItemHeight,
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          double itemWidth = constraints.maxWidth / 4;
          // '本月' 宽度
          Size targetWidth = BaseUtils.boundingTextSize(context, '本月', DefaultTextStyle.of(context).style);
          // 占位宽度
          double footprintWidth = itemWidth / 2 - targetWidth.width / 2;
          return Row(
            children: [
              SizedBox(width: footprintWidth),
              Text("自定义:", style: TextStyle(color: isSelect ? systemColor : DefaultTextStyle.of(context).style.color)),
              Expanded(
                child: InkWell(
                  onTap: editCustomizeStartDate,
                  child: Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(border: Border(top: BorderSide.none, left: BorderSide.none, right: BorderSide.none, bottom: BorderSide(width: 1.0, color: customizeStart != null ? Color(0xFF5E96F4) : Color(0xFFEFEFEF)))),
                    child: Text(getCustomizeStartDateShowText(), style: TextStyle(color: isSelect ? systemColor : DefaultTextStyle.of(context).style.color)),
                  ),
                ),
              ),
              Text('至'),
              Expanded(
                child: InkWell(
                  onTap: editCustomizeEndDate,
                  child: Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.symmetric(horizontal: 10),
                    decoration: BoxDecoration(border: Border(top: BorderSide.none, left: BorderSide.none, right: BorderSide.none, bottom: BorderSide(width: 1.0, color: customizeStart != null ? Color(0xFF5E96F4) : Color(0xFFEFEFEF)))),
                    child: Text(getCustomizeEndDateShowText(), style: TextStyle(color: isSelect ? systemColor : DefaultTextStyle.of(context).style.color)),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  void editCustomizeStartDate() {
    BaseComponentUtils.openDatePicker(context, currentDate: customizeStart ?? null, onDateChanged: (DateTime changed) {
      customizeStart = changed;

      ///当设置开始日期大于结束日期时，自动将结束日期等于开始日期
      if (customizeEnd != null && customizeStart.isAfter(customizeEnd)) {
        // customizeEnd = customizeStart;
        BaseUtils.showToast("开始时间不能大于结束时间");
      }
      if (customizeStart != null && customizeEnd != null) {
        ///由于选择后就关闭，所以不再需要刷新
        widget.selectResultCallback(BaseDateTypeEnum.customize, BaseDateUtil.dateTimeAddTimeZone(customizeStart), BaseDateUtil.dateTimeAddTimeZone(customizeEnd));
        BaseRouterUtil.getInstance().pop();
      } else {
        setState(() {});
      }
    });
  }

  void editCustomizeEndDate() {
    BaseComponentUtils.openDatePicker(context, currentDate: customizeEnd ?? null, onDateChanged: (DateTime changed) {
      customizeEnd = changed;

      ///当设置结束日期小于开始日期时，自动将结束日期等于开始日期
      if (customizeStart != null && customizeEnd.isBefore(customizeStart)) {
        // customizeEnd = customizeStart;
        BaseUtils.showToast("结束时间不能小于开始时间");
      }
      if (customizeStart != null && customizeEnd != null) {
        ///由于选择后就关闭，所以不再需要刷新
        widget.selectResultCallback(BaseDateTypeEnum.customize, BaseDateUtil.dateTimeAddTimeZone(customizeStart), BaseDateUtil.dateTimeAddTimeZone(customizeEnd));
        BaseRouterUtil.getInstance().pop();
      } else {
        setState(() {});
      }
    });
  }

  String getCustomizeStartDateShowText() {
    if (customizeStart == null) return "开始时间";
    if (widget.setCustomizeDateDisplayed != null) widget.setCustomizeDateDisplayed(customizeStart);
    return "${customizeStart.year}-${BaseTransformUtil.format(customizeStart.month)}-${BaseTransformUtil.format(customizeStart.day)}";
  }

  String getCustomizeEndDateShowText() {
    if (customizeEnd == null) return "结束时间";
    if (widget.setCustomizeDateDisplayed != null) widget.setCustomizeDateDisplayed(customizeEnd);
    return "${customizeEnd.year}-${BaseTransformUtil.format(customizeEnd.month)}-${BaseTransformUtil.format(customizeEnd.day)}";
  }

  /// 点击标签
  void onClickLabel(BaseDateTypeEnum typeEnum) {
    dateTypeEnum = typeEnum;
    List<DateTime> labelDateTime = BaseDateUtil.getTimePeriodForDateTypeEnum(typeEnum);
    widget.selectResultCallback(dateTypeEnum, BaseDateUtil.dateTimeAddTimeZone(labelDateTime[0]), BaseDateUtil.dateTimeAddTimeZone(labelDateTime[1]));
    BaseRouterUtil.getInstance().pop();
  }
}
